package com.mainbo.modular.system.controller;

import cn.stylefeng.roses.core.base.controller.BaseController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.util.Result;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.system.dao.PtClassMapper;
import com.mainbo.modular.system.model.PtClass;
import com.mainbo.modular.system.model.PtSchoolBuilding;
import com.mainbo.modular.system.model.meta.ConfigConstants;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.model.meta.vo.Meta;
import com.mainbo.modular.system.service.IPtSchoolBuildingService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import com.mainbo.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import com.mainbo.modular.system.model.PtSchoolClassroom;
import com.mainbo.modular.system.service.IPtSchoolClassroomService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 控制器
 *
 * @author fengshuonan
 * @Date 2020-03-05 17:23:43
 */
@Controller
@RequestMapping("/ptSchoolClassroom")
public class PtSchoolClassroomController extends BaseController {
    private  static final Logger logger= LoggerFactory.getLogger(PtSchoolClassroomController.class);

    private String PREFIX = "/system/ptSchoolClassroom/";

    @Autowired
    private IPtSchoolClassroomService ptSchoolClassroomService;
    @Resource
    private IPtSchoolBuildingService ptSchoolBuildingService;
    @Resource
    private PtClassMapper classMapper;
    /**
     * 进入管理教室页面
     * @param m
     * @return
     */
    @RequestMapping("/toManagerClassRoom")
    public String toManagerClassRoom(Model m, String buildingId) {
        List<Meta> classTypes=MetaUtils.listMeta(ConfigConstants.CLASSROOM_TYPE);
        m.addAttribute("classTypes",classTypes);
        m.addAttribute("buildingId",buildingId);
      return   PREFIX + "ptSchoolClassroom.html";
    }
    /**

     * @param cr
     * @return
     */
    @RequestMapping("/findListClassRoom")
    @ResponseBody
    public Object findListClassRoom(PtSchoolClassroom cr) {
        EntityWrapper<PtSchoolClassroom> wrapper=new EntityWrapper<>();
        if(StringUtils.isNotBlank(cr.getName())){
            String searchName = cr.getName();
            wrapper.eq("name",searchName );
        }
        if(null!=cr.getClassroomTypeId()){
            Integer classroomTypeId = cr.getClassroomTypeId();
            wrapper.eq("classroom_type_id",classroomTypeId);
        }
        wrapper.eq("building_id",cr.getBuildingId());
        wrapper.eq("deleted",0);
        wrapper.orderBy("create_time",false);
        List<PtSchoolClassroom> classrooms = ptSchoolClassroomService.selectList(wrapper);
        return   classrooms;
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/ptSchoolClassroom_add")
    public String ptSchoolClassroomAdd(String buildingId,Model m) {
        List<Meta> classTypes=MetaUtils.listMeta(ConfigConstants.CLASSROOM_TYPE);
        m.addAttribute("classTypes",classTypes);
        PtSchoolBuilding building = ptSchoolBuildingService.selectById(buildingId);
        m.addAttribute("building",building);
        return PREFIX + "ptSchoolClassroom_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/ptSchoolClassroom_update/{ptSchoolClassroomId}")
    public String ptSchoolClassroomUpdate(@PathVariable String ptSchoolClassroomId, Model model) {
        PtSchoolClassroom ptSchoolClassroom = ptSchoolClassroomService.selectById(ptSchoolClassroomId);
        model.addAttribute("item",ptSchoolClassroom);
        List<Meta> classTypes=MetaUtils.listMeta(ConfigConstants.CLASSROOM_TYPE);
        model.addAttribute("classTypes",classTypes);
        LogObjectHolder.me().set(ptSchoolClassroom);
        return PREFIX + "ptSchoolClassroom_edit.html";
    }
    /**
     * 根据id查看教室详情
     * @param m
     * @param id
     * @return
     */
    @RequestMapping("/detail/{id}")
    public String detailClassRoom(Model m ,@PathVariable String id){
        PtSchoolClassroom classRoom = ptSchoolClassroomService.selectById(id);
        String typeName = MetaUtils.getMeta(classRoom.getClassroomTypeId()).getName();
        m.addAttribute("typeName",typeName);
        m.addAttribute("classRoom",classRoom);
        return PREFIX + "ptSchoolClassroom_info.html";
    }
    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(PtSchoolClassroom ptSchoolClassroom) {
        Result result = new Result();
        try {
            ptSchoolClassroom.setCreateTime(new Date());
            ptSchoolClassroom.setIsUsed(0);
            String position = ptSchoolClassroom.getBuildingName() + ptSchoolClassroom.getFloor() + "层" + ptSchoolClassroom.getSerialNo() + "号";
            ptSchoolClassroom.setClassroomPosition(position);
            boolean save = ptSchoolClassroomService.insert(ptSchoolClassroom);
            if(save){
                ptSchoolClassroomService.sendMessage(MessageTypes.CLASSROOM_ADD,ptSchoolClassroom);
            }
            result.setMsg("操作成功");
            result.setCode(Result.SUCCESS);
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setCode(Result.FAIL);
        }
        return result;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete/{id}")
    @ResponseBody
    public Object delete(@PathVariable String id) {
        Result result = new Result();
        try {
            if(StringUtils.isNotBlank(id)){
                ptSchoolClassroomService.updateDeleteFlag(id);

            }
            result.setCode(Result.SUCCESS);
            result.setMsg("操作成功");
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setCode(Result.FAIL);
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(PtSchoolClassroom ptSchoolClassroom) {
        Result result = new Result();
        try {
            ptSchoolClassroom.setModifyTime(new Date());
            String position = ptSchoolClassroom.getBuildingName() + ptSchoolClassroom.getFloor() + "层" + ptSchoolClassroom.getSerialNo() + "号";
            ptSchoolClassroom.setClassroomPosition(position);
            boolean update = ptSchoolClassroomService.updateById(ptSchoolClassroom);
            if (update){
                PtSchoolClassroom classRoom = ptSchoolClassroomService.selectById(ptSchoolClassroom.getId());
                ptSchoolClassroomService.sendMessage(MessageTypes.CLASSROOM_UPDATE,classRoom);
            }
            result.setCode(Result.SUCCESS);
            result.setMsg("操作成功");
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setCode(Result.FAIL);
        }
        return result;
    }
    /**
     * 获取所有未被分配得教室列表
     * @param m
     * @return
     */
    @RequestMapping("/listClassRoomUnuse")
    public String listClassRoomUnuse(Model m,String classId,String orgId){
        EntityWrapper<PtSchoolBuilding> building = new EntityWrapper<>();
        building.eq("org_id",orgId);
        List<PtSchoolBuilding> buildingList = ptSchoolBuildingService.selectList(building);
        if(!CollectionUtils.isEmpty(buildingList)){
            ArrayList<String> idList = new ArrayList<>();
            for (PtSchoolBuilding sch:buildingList
            ) {
                idList.add(sch.getId());
            }
            List<PtSchoolClassroom> crList = ptSchoolClassroomService.listByBuildingId(idList);
            m.addAttribute("classId",classId);
            m.addAttribute("crList",crList);
            m.addAttribute("orgId",orgId);
        }
        return PREFIX + "ptSchoolClassroom_addToClass.html";
    }

    /**
     * 根据教室类型获取教室
     * @param cr
     * @return
     */
    @RequestMapping("/listCrByType")
    @ResponseBody
    public Result listCrByType(PtSchoolClassroom cr){
        Result result = new Result();
        EntityWrapper<PtSchoolClassroom> entityWrapper=new EntityWrapper<>();
        entityWrapper.eq("deleted",0);
        entityWrapper.eq("enable",1);
        entityWrapper.eq("org_id",cr.getOrgId());
        entityWrapper.eq("classroom_type_id",cr.getClassroomTypeId());
        List<PtSchoolClassroom> crList = ptSchoolClassroomService.selectList(entityWrapper);
        if(!CollectionUtils.isEmpty(crList)){
            result.setData(crList);
        }
        return result;
    }


    /**
     * 为班级分配教室
     * @param classroomId
     * @return
     */
    @RequestMapping("/addClassRoomToClass")
    @ResponseBody
    public Result addClassRoomToClass(String classroomId,String classId){
        Result result = new Result();
        try {
            if(StringUtils.isNotBlank(classroomId)){
                PtSchoolClassroom classRoom = ptSchoolClassroomService.selectById(classroomId);
                classRoom.setIsUsed(1);

                PtClass classInfo = classMapper.selectById(classId);
                if(StringUtils.isNotBlank(classInfo.getClassroomId())){
                    PtSchoolClassroom lastClassRoom = ptSchoolClassroomService.selectById(classInfo.getClassroomId());
                    lastClassRoom.setIsUsed(0);
                    ptSchoolClassroomService.updateById(lastClassRoom);
                }
                classInfo.setClassroomName(classRoom.getBuildingName()+classRoom.getName());
                classInfo.setClassroomId(classroomId);
                ptSchoolClassroomService.updateById(classRoom);
                //classRoom.setClassId(classId);
                ptSchoolClassroomService.sendMessage(MessageTypes.CLASSROOM_SET,classRoom);
                classMapper.updateById(classInfo);

            }
            result.setCode(Result.SUCCESS);
            result.setMsg("设置教室成功");
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            result.setMsg("操作失败");
            logger.error("设置教室失败",e);
        }
        return result;
    }
    /**
     * 班级解除教室绑定
     * @param id
     * @return
     */
    @RequestMapping("/ClassRemoveClassRoom")
    @ResponseBody
    @Transactional
    public Result ClassRemoveClassRoom(String id){
        Result result = new Result();
        try {
            PtClass classInfo1 = classMapper.selectById(id);
            String classroomId = classInfo1.getClassroomId();
            if(StringUtils.isNotBlank(classroomId)){
                PtSchoolClassroom classRoom = ptSchoolClassroomService.selectById(classroomId);
                classRoom.setIsUsed(0);
                ptSchoolClassroomService.updateById(classRoom);
               // classRoom.setClassId(id);
                ptSchoolClassroomService.sendMessage(MessageTypes.CLASSROOM_SET,classRoom);
            }
            PtClass classInfo = new PtClass();
            classInfo.setClassroomId("");
            classInfo.setClassroomName("");
            classInfo.setId(id);
            classMapper.updateById(classInfo);
            result.setMsg("解除教室成功");
            result.setCode(Result.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(Result.FAIL);
            result.setMsg("操作失败");
        }
        return result;
    }
}
